package equappcontrollers
/*
  基本数据信息的加载
 */

import (
	"github.com/astaxie/beego"
	"fmt"
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
	"smartcap-api/models"
)


type MainController struct {
	beego.Controller
}


func (c *MainController) Get() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func (c *MainController) optionsAllowCross() {
	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "http://localhost:14000")       //允许访问源
	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")    //允许post访问
	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization") //header的类型
	c.Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
	c.Ctx.ResponseWriter.Header().Set("content-type", "application/json") //返回数据格式是json
}


func (c *MainController) Options() {
	c.optionsAllowCross() //允许跨域
	c.Data["json"] = map[string]interface{}{"status": 200, "message": "ok", "moreinfo": ""}
	c.ServeJSON()
}




//设备开机,更改设备开关机状态为开机,并返回设备用户名
func (c *MainController) Equstartup() {
	fmt.Println("开机后，获取设备状态信息")
	FileLogs.Info("开机后，获取设备状态信息")
	deviceid := c.GetString("deviceid")
    fmt.Println("开机设备id:",deviceid)

	//修改设备开机状态
	o := orm.NewOrm()
	_, err := o.Raw("update label_info set online = ? where labelid = ?", "在线",deviceid).Exec()

	var devicerows []models.LabelInfo
	_, err1 := o.Raw("SELECT * FROM label_info WHERE labelid = ?  ",deviceid).QueryRows(&devicerows)

	username := ""
	company := models.QueryCompanyByLabelid(deviceid)
	//companyid := webappcontrollers.QueryCompanyidByCompany(company)
	if err1 == nil {
		for _, devicerow := range devicerows {
			username = devicerow.Labeluser
			fmt.Println(username)
		}
	}

	type DATA struct {
		Deviceid string
		Username string
		Company string
	}
	type JSONS struct {
		//必须的大写开头
		Error_code int
		DATA DATA
	}

	if err != nil{
		data := &JSONS{1,DATA{deviceid,"null","null"}}
		c.Data["json"] = data
		c.ServeJSON()
	}else {
		data := &JSONS{0, DATA{deviceid,username,company}}
		c.Data["json"] = data
		c.ServeJSON()
	}
	//c.Ctx.WriteString(" successful")
}



//设备关机，更改设备状态为关机
func (c *MainController) Equturnoff() {
	FileLogs.Info("=======设备关机======")

	deviceid := c.GetString("deviceid")
	FileLogs.Info("设备id:",deviceid)
	//修改设备开机状态
	o := orm.NewOrm()
	_, err := o.Raw("update label_info set online = ? where labelid = ?", "不在线",deviceid).Exec()

	type DATA struct {
		Deviceid string
	}
	type JSONS struct {
		//必须的大写开头
		Error_code int
		DATA DATA
	}

	if err != nil{
		data := &JSONS{1,DATA{deviceid}}
		c.Data["json"] = data
		c.ServeJSON()
	}else {

		data := &JSONS{0, DATA{deviceid}}
		c.Data["json"] = data
		c.ServeJSON()
	}

	//c.Ctx.WriteString("test successful")
}


//每隔一分钟上传状态信息：电池电量
func (c *MainController) Statusinfo() {
	FileLogs.Info("=======状态信息上传======")
    deviceid := c.GetString("deviceid" )
	remainingcapacity := c.GetString("remainingcapacity")
	o := orm.NewOrm()

	defer FileLogs.Info("======退出状态信息函数======")

	//查询该设备所属公司
	var labelrows []models.LabelInfo
	if _, err := o.Raw("SELECT * FROM label_info  where labelid = ?",deviceid ).QueryRows(&labelrows); err != nil{
		fmt.Println("err")
		return
	}
	var company = ""
	for _,labelrow := range labelrows{
		company = labelrow.Unit
		break
	}

	_, err := o.Raw("update label_info set electricquantity = ? where labelid = ?", remainingcapacity,deviceid).Exec()
	remcap,_ := strconv.Atoi(remainingcapacity)

	timeUnix:=time.Now().Unix()
	timeStr:=time.Now().Format("2006-01-02 15:04:05")

	//电量如果低于30%，记录到告警信息中
    if remcap <30 {
		alramdata := models.AlarmrecordInfo{Deviceid:deviceid, Devicetype:"安全帽标签",Company:company, Alarmtype:"低电量告警", Alarmstamp:timeUnix,Alarmtime:timeStr}
		models.AddAlarm(&alramdata)
	}

	type DATA struct {
		Deviceid string
	}

	type JSONS struct {
		//必须的大写开头
		Error_code int
		DATA DATA
	}

	if err != nil  {
		data := &JSONS{1,DATA{deviceid}}
		c.Data["json"] = data
		c.ServeJSON()
	}else {
		data := &JSONS{0, DATA{deviceid}}
		c.Data["json"] = data
		c.ServeJSON()
	}

}


//每10秒钟调用一次心跳包： 心率 近电状态 佩戴状态
func (c *MainController) Heartandtime() {
	deviceid := c.GetString("deviceid")
	badhandstatus := c.GetString("badhandstatus")
	wearingstatus := c.GetString("wearingstatus")
	nearelectricity := c.GetString("nearelectricity")

	if wearingstatus == "0"{
		wearingstatus = "佩戴"
	}else if wearingstatus == "1" {
		wearingstatus = "未佩戴"
	}

	if nearelectricity == "0"{
		nearelectricity = "近电"
	}else if nearelectricity == "1"{
		nearelectricity = "未近电"
	}

	o := orm.NewOrm()
	//查询该设备所属公司
	var labelrows []models.LabelInfo
	if _, err := o.Raw("SELECT * FROM label_info  where labelid = ?",deviceid ).QueryRows(&labelrows); err != nil{
		fmt.Println("err")
		return
	}
	var company = ""
	for _,labelrow := range labelrows{
		company = labelrow.Unit
		break
	}
     defer FileLogs.Info("======退出心跳包函数======")
	//修改设备状态
	_, err1 := o.Raw("update label_info set badhandstatus = ? , wearingstatus = ?, nearelectricity = ? where labelid = ?", badhandstatus,wearingstatus,nearelectricity,deviceid).Exec()
    //获取设备当前网络状态
	var devicerows []models.LabelInfo
	_, err2 := o.Raw("SELECT * FROM label_info WHERE labelid = ?  ",deviceid).QueryRows(&devicerows)
	timeUnix:=time.Now().Unix()
	timeStr:=time.Now().Format("2006-01-02 15:04:05")
	badsta,_ := strconv.Atoi(badhandstatus)

	//记录心率告警
	if badsta >120 {
		alramdata := models.AlarmrecordInfo{Deviceid:deviceid, Devicetype:"安全帽标签",Company:company,Alarmtype:"心率告警", Alarmstamp:timeUnix,Alarmtime:timeStr}
		models.AddAlarm(&alramdata)
	}
	//记录佩戴状态告警
	if wearingstatus == "未佩戴" {
		alramdata := models.AlarmrecordInfo{Deviceid:deviceid, Devicetype:"安全帽标签",Company:company,Alarmtype:"未佩戴告警", Alarmstamp:timeUnix,Alarmtime:timeStr}
		models.AddAlarm(&alramdata)
	}
	//记录近电告警
	if nearelectricity == "近电" {
		alramdata := models.AlarmrecordInfo{Deviceid:deviceid, Devicetype:"安全帽标签",Company:company,Alarmtype:"近电告警", Alarmstamp:timeUnix,Alarmtime:timeStr}
		models.AddAlarm(&alramdata)
	}

	networkstatus := ""
	opencamera := ""
	alarmflag := ""
	for _,devicerow := range devicerows {
		networkstatus = devicerow.Networkstatus
		opencamera = devicerow.Opencamera
		alarmflag = devicerow.Alarmflag
		//改回摄像头状态位，防止不断调取摄像头
		if(opencamera == "0"){
			_, err1 := o.Raw("update label_info set opencamera = ? where labelid = ?", "1",deviceid).Exec()
			fmt.Println(err1)
		}
	}

	type DATA struct {
		Deviceid string
		Networkstatus string
		Opencamera string
		Alarmflag  string
		Timestamp int64
	}

	type JSONS struct {
		//必须的大写开头
		Error_code int
		DATA DATA
	}

	if (err1 != nil) && (err2 != nil) {
		data := &JSONS{1,DATA{deviceid,"null","null","null",0}}
		c.Data["json"] = data
		c.ServeJSON()
	}else {
		data := &JSONS{0, DATA{deviceid,networkstatus,opencamera,alarmflag,timeUnix}}
		c.Data["json"] = data
		c.ServeJSON()
	}
}

//软件升级和恢复出厂设置
func (c *MainController) Updata() {
	fmt.Println("软件升级")
	c.Ctx.WriteString("test successful")
}







